<template>
  <div>
    <Card title="主表" :bordered="false">
      <Table :data-source="dataRef.dataSource" :columns="mainColumns" :pagination="false">
        <template #bodyCell="{ record, column }">
          <template v-if="column.dataIndex == '_name'">
            <Select
              style="width: 100%"
              v-model:value="record[column.dataIndex]"
              show-search
              optionFilterProp="label"
              :options="fieldsDataOptions"
            />
          </template>
        </template>
      </Table>
    </Card>
    <Card title="主表基础数据清洗" :bordered="false">
      <div v-for="(item, index) in dataRef.basicFields" :key="index" style="margin-bottom: 10px">
        <checkbox style="margin-bottom: 10px" v-model:checked="item.checked">
          {{ item.title }} （勾选后才能清洗数据）
        </checkbox>
        <Table :data-source="item.options" :columns="childColumns" :pagination="false">
          <template #bodyCell="{ record, column }">
            <template v-if="column.dataIndex == 'otherVal'">
              <Input style="width: 100%" v-model:value="record[column.dataIndex]" />
            </template>
          </template>
        </Table>
      </div>
    </Card>
  </div>
</template>
<script lang="ts" setup>
  import { ref, watch, nextTick } from 'vue';
  import { Input, Card, Table, Select, Checkbox, Modal } from 'ant-design-vue';
  import { mainColumns, childColumns } from './supscribeTableView.data';
  import { isArray, isEmpty } from '/@/utils/is';
  import { getFieldsWithRelated, getFormGetFields } from '/@/api/flowManage/flowManage';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';
  import { Console } from 'console';

  const props = defineProps({
    stateData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    formCode: {
      type: String,
      default: '',
    },
    fieldsDataOptions: {
      type: Array,
      default: () => {
        return [];
      },
    },
    isUpdate: {
      type: Boolean,
      default: false,
    },
  });
  const emit = defineEmits(['success']);
  const { createMessage, createConfirm } = useMessage();
  const dataRef = ref<Recordable>({
    dataSource: [],
    cells: [],
    basicFields: [],
    name: '',
  });
  watch(
    () => props.stateData,
    async (newVal) => {
      console.log('newVal', newVal);
      if (isEmpty(newVal)) return;
      await nextTick();
      const newVals = cloneDeep(newVal);
      const { name, basicFields, fieldMap } = newVals;
      dataRef.value.dataSource = [];
      dataRef.value.basicFields = [];
      dataRef.value.cells = [];
      dataRef.value.name = name ?? '';
      await getFormGetFieldsData();
      await getFormGetFieldsDataMain();
      dataRef.value.dataSource = [...formGetFieldsDataMain.value];
      if (!isEmpty(fieldMap)) {
        console.log('fieldMap', fieldMap);
        dataRef.value.dataSource.forEach((item) => {
          if (Reflect.has(fieldMap, item.name)) {
            item._name = fieldMap[item.name];
          } else {
            item._name = '';
          }
        });
      }
      console.log('dataRef.value.dataSource', dataRef.value.dataSource);
      if (basicFields && isArray(basicFields) && basicFields?.length) {
        dataRef.value.basicFields = basicFields;
      }
      console.log('dataRef', dataRef.value);
    },
    {
      immediate: true,
      deep: true,
    },
  );

  const handleSubmit = () => {
    if (!dataRef.value.name) {
      createMessage.warning('名称不能为空');
      return;
    }
    console.log('handleSubmit dataRef.value', dataRef.value);
    emit('success', dataRef.value);
  };

  //获取主表数据
  const formGetFieldsDataMain = ref([]);
  const getFormGetFieldsDataMain = async () => {
    if (!props.formCode) return;
    const res = await getFormGetFields({ formCode: props.formCode });
    formGetFieldsDataMain.value = res || [];
  };

  const formGetFieldsData = ref<Recordable[]>([]);
  //获取数据
  const getFormGetFieldsData = async () => {
    formGetFieldsData.value = [];
    try {
      if (!props.formCode) return;
      await getFieldsWithRelated({ formCode: props.formCode }).then((res) => {
        formGetFieldsData.value = res || [];
        formGetFieldsData.value.forEach((item: Recordable) => {
          delete item.options;
          item.value = item.name;
          item.label = item.title;
        });
      });
    } catch (err) {
      console.log('getFieldsWithRelated', err);
    }
  };

  defineExpose({
    dataRef,
  });
</script>
<style scoped>
  .name::before {
    display: inline-block;
    margin-right: 4px;
    color: #ff4d4f;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    line-height: 1;
    content: '*';
  }
  .td_selected_bg {
    background-color: #00cc00;
  }
  .tabStyle_1 td {
    padding: 2px 7px;
  }
</style>
